<template>
  <div class="main-container">
    <TableHeadSearch @searchForm="searchForm" queryCode="userRoleList"/>
    <TableBody
      ref="tableBody"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableColumns="tableColumns"
      :tableOperations="tableOperations"
      :tableData="dataList"
    >
      <template #tableConfig>
        <div
          class="flex justify-between padding"
          style="border-bottom: 1px dashed var(--el-border-color-light)"
        >
          <el-link :underline="false">表格设置</el-link>
          <div>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.border">表格边框</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.stripe">斑马纹</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.multiSelect">多选</el-checkbox>
            </span>
          
            <SortableTable
              class="margin-left"
              :table-props="tableColumns"
              @update="onUpdateTable"
            />
          </div>
        </div>
      </template>
    </TableBody>
    <TableFooter
      ref="tableFooter"
      @refresh="doRefresh"
      @pageChanged="doRefresh"
    />
   
  <Dialog ref="dialog" title="编辑信息" :form-items="formItems">
      <template #content>
        <BaseForm
          ref="baseForm"
          :form-items="formItems"
        ></BaseForm>
      </template>
  </Dialog>
  </div>
</template>


<script lang="tsx" setup>
import { ElMessage } from 'element-plus';
import {computed,onMounted, reactive, ref,toRef} from "vue";

import {
  showConfirmBox,
  showErrorMessage,
  showInfoMessage,
  showSuccessMessage,
} from "@/components/types";
import { useDataTable, usePost } from "@/hooks";
import { queryUserRoleList,saveUserRole,updateUserRole,deleteBatchUserRole,findRole } from "@/api/url";
import type { TableFooter,BaseFormType, DialogType } from "@/components/types";
import {
  Delete,
  CirclePlus,
  Refresh as RefreshIcon,
} from "@element-plus/icons";
import { each } from 'lodash';
const {
  handleSuccess,
  selectRows,
  dataList,
  tableConfig,
  tableLoading,
  handleSelectionChange,
} = useDataTable();
const post = usePost();
const tableColumns = reactive([
  { label: "用户名", 
    prop: "userName", 
    checked:true,
  },
   { label: "姓名", 
    prop: "realName", 
    checked:true,
  },
   { label: "所在部门", 
    prop: "departmentName", 
    checked:true,
  },
  { label: "角色名", 
    prop: "roleName", 
    width: "500",
    checked:true,
  },
  //  { label: "角色名ID", 
  //   prop: "roleOids", 
  //   checked:true,
  // },
  
  

]);
const tableOperations = reactive([
  {
    text: "分配角色",
    key: "edit",
    type: "primary",
    size: "small",
    handler: (row: any) => handleEdit(row),
  },
]);

let roleResultList :  any ;
function findRoles() {
  post({
    url: findRole,
    data: {
      
    },
  })
  .then((res: any) => {
    roleResultList = res.data;
  })
  .catch(console.log);
}

let selectedRoles : any  ;
const roleOidsFormItem = { label: "选中角色ID", 
    type: 'input',
    name: "roleOids", 
    value: '',
    hidden: true,
    reset() {
                this.value = "";
            },
};
const keyOidsFormItem =  { label: "keyOids", 
    type: 'input',
    name: "keyOids", 
    value: [],
    hidden: true,
    reset() {
                this.value = [];
            },
  };
const roleFormItem =  { 
    name: "assignedRoleOids",
    type: 'check-group',
    label: "分配角色",
    placeholder: "请选择角色名称",
    value: [],
    selectedValue: selectedRoles,
    checkOptions: {},
    onChange: (item: any) => {
        keyOidsFormItem.value = item.selectedValue;
        roleOidsFormItem.value = item.selecteValue;
    }, 
    reset() {
                this.value = [];
            },
  };
 
const formItems = reactive([
  
  { label: "OID", 
    type: 'input',
    name: "versionNo", 
    value: '',
    hidden: true,
    reset() {
                this.value = "";
            },
  },
  keyOidsFormItem,
  { label: "角色OID", 
    type: 'input',
    name: "roleOid", 
    value: '',
    hidden: true,
    reset() {
                this.value = "";
            },
  },
  
  { label: "用户OID", 
    type: 'input',
    name: "userOid", 
    value: '',
    hidden: true, 
    reset() {
                this.value = "";
            },
  },
 roleOidsFormItem,
 roleFormItem,

]);

const tableFooter = ref<TableFooter>();
const dialog = ref<DialogType>();
const baseForm = ref<BaseFormType>();
function handleEdit(data: any) {
  onUpdateItem(data);
}
const onUpdateItem = (item: any) => {
  formItems.forEach((it) => {
    const propName = item[it.name];
    var roleOids = item['roleOids'];
    //更新选中的角色
    roleOidsFormItem.value = roleOids;
    var roleOidArray: Array<number> = [];
    if(it.name === 'assignedRoleOids'){
      if(roleOids != undefined && roleOids.length > 0) {
         var allRoles: Array<string> = roleOids.split(",");
         allRoles.forEach((eachItem : string )=> {
           roleOidArray.push(parseInt(eachItem));
         });
      }
      it.selectedValue = roleOidArray;
    }
    it.value = propName;
  });
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(updateUserRole,baseForm.value?.generatorParams())
      keyOidsFormItem.value = [];
      dialog.value?.close();
    }, 1000);
  });
};

function doRefresh() {
   let params = {
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryUserRoleList,params);
}

function queryList(url: string, params: any) {
  post({
    url: url,
    data: params,
  })
    .then((res: any) => {
      const obj = {
        data: res.data,
      };
      handleSuccess(obj);
      tableFooter.value?.setTotalSize(res.pageUI.total);
    })
    .catch(console.log);
}

function submitForm(submitUrl: string ,params: any) {
   post({
    url: submitUrl,
    data: params,    
  })
  .then((res: any) => {
     ElMessage.success("数据提交成功！");
     doRefresh();
  })
  .catch(console.log);
}

const onAddItem = () => {
  baseForm.value?.resetParams();
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(saveUserRole,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
   
  });
};

function onDeleteItem(data: any) {
  if (data.length > 0) {
    showConfirmBox("是否要删除此数据项，删除后不恢复？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        let params: number[] = [];
        data.forEach((item: { userRoleOid: any }) => {
          params.push(item.userRoleOid);
        });
        post({
          url: deleteBatchUserRole,
          data: {
            keyOids: params,
          },
        })
          .then(() => {
            doRefresh();
            showSuccessMessage("删除成功");
          })
          .catch(console.log);
      })
      .catch(() => {
        showInfoMessage("取消删除");
      });
  } else {
    showErrorMessage("请选择要删除的数据项");
  }
}

function searchForm(data: any) {
    let params = {
    searchConditionVOList: data,
    page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryUserRoleList,params);
}

function onUpdateTable(temp: Array<TablePropsType>) {
  tableColumns.length = 0;
  tableColumns.push(...temp.filter((it: TablePropsType) => it.checked));
}

roleFormItem.checkOptions = computed(() => {
  return roleResultList.map((it: any) => {
    return {
      label: it.name,
      value: it.roleOid,
    };
  });
});

onMounted(doRefresh);
onMounted(findRoles);
</script>
<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>
